//index.js
//获取应用实例
const app = getApp();
var base = require('../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数
const PAGES = require('../../utils/pages.js')
const { user, sqLogin } = require('../../lib/user.js')
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    _t: [],
    isShowLogin: 0
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    this.setData({
      isShowLogin: options.isShowLogin,
      hasUserInfo: options.isShowLogin == 1 ? false : true,
    });
    // 在没有 open-type=getUserInfo 版本的兼容处理
    user.userInfoReadyCallback = res => {
      wx.switchTab({
        url: PAGES.mainPage,
      })
    }
    var that = this;
    wx.getUserInfo({
      success: res => {
        app.globalData.userInfo = res.userInfo
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          isShowLogin: 1,
        })
        this.gotoHome();
      }, fail: function (res) {
        that.gotoHome();
      }

    })
    this.setData({
      _t: base._t(), //翻译
    });
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true,
      isShowLogin: 1,
    })
    this.gotoHome();
  },
  //前往首页
  gotoHome: function () {
    if (this.data.isShowLogin == 1) {
      sqLogin();
    } else {
      wx.switchTab({
        url: PAGES.mainPage,
      })
    }
  },
  jumpHomeTap: function () {
    wx.switchTab({
      url: PAGES.mainPage,
    })
  },
  //通过绑定手机号登录
  　　getPhoneNumber: function (e) {
    var ivObj = e.detail.iv
    var telObj = e.detail.encryptedData
    var codeObj = "";
    var that = this;
    //------执行Login---------
    wx.login({
      success: res => {
        console.log('code转换', res.code); 

　　　　　　//用code传给服务器调换session_key
        wx.request({
          url: 'https://你的接口文件路径', //接口地址
          data: {
            code: res.code,
            encryptedData: telObj,
            iv: ivObj
          },
          success: function (res) {
            phoneObj = res.data.phoneNumber;
            console.log("手机号=", phoneObj)
            wx.setStorage({   //存储数据并准备发送给下一页使用
              key: "phoneObj",
              data: res.data.phoneNumber,
            })
          }
        })

        //-----------------是否授权，授权通过进入主页面，授权拒绝则停留在登陆界面
        if (e.detail.errMsg == 'getPhoneNumber:user deny') { //用户点击拒绝
          wx.navigateTo({
            url: '../index/index',
          })
        } else { //允许授权执行跳转
          wx.navigateTo({
            url: '../test/test',
          })
        }
      }
    });
},
})
